import { PlatFormId } from '../define/PlatformDefine';

export default class SaveModel {
  public static _save: SaveModel;
  public static get ins(): SaveModel {
    if (!this._save) {
      this._save = new SaveModel();
    }
    return this._save;
  }

  public platform: PlatFormId = PlatFormId.H5;

  public getModel(key: string): any {
    let value: any;
    switch (this.platform) {
      case PlatFormId.H5:
        value = this.getModelFromStorage(key);
        break;
    }
    return value;
  }

  public saveModel(key: string, value: any): void {
    switch (this.platform) {
      case PlatFormId.H5:
        this.setModelFromStorage(key, value);
        break;
    }
  }

  private getModelFromStorage(key: string): any {
    let valueStr: string = localStorage.getItem(key);
    let value: any = null;
    if (valueStr) value = JSON.parse(valueStr);
    return value;
  }

  private setModelFromStorage(key: string, value: any): void {
    let valueStr: string = JSON.stringify(value);
    localStorage.setItem(key, valueStr);
  }

  public clearData(key?: string): void {
    if (key) {
      localStorage.removeItem(key);
    } else {
      localStorage.clear();
    }
  }
}
